#include "gregion.h"

GRegion::GRegion(QWidget *parent)
    : QDialog(parent)
{
	setupUi(this);
    setWindowFlags ( Qt::Window );
}


void GRegion::init()
{
	     RowUnique.clear();
       treeView->deleteLater();
	     delete treeView ;
	     treeView = new QTreeView(this);
       treeView->setObjectName(QString::fromUtf8("treeView"));
       gridLayout->addWidget(treeView, 1, 0, 3, 1);
	     //////treeView->clear();
	     treeView->clearSelection();
       ReadModel = new QSqlQueryModel();
       ReadModel->setQuery(RICHIESTA_PAESI,liner->current());
	      QSqlQuery init("",liner->current());
        query = init;  ///// QSqlQuery query;
	      DisplayFields.clear();
	      DTrFields.clear();
	     //////    id  	 root_id  	 name  	 lft  	 rgt  	 cpa  	 msm  	 childs  	 level  	 lower  	 upper
       DisplayFields << "id" << "root_id" << "name" << "msm" << "cpa" << "level" << "import_id" << "childs" << "lft" << "rgt";
	     DTrFields << tr("ID") << tr("Parente") << tr("NOME") << tr("MSm") << tr("CPA") << tr("Livello") << tr("CityId") << tr("Sottocategorie") << tr("Sinistra") << tr("Destra");  ////  << tr("Livello")
	
	      model = new QStandardItemModel();  //// cat_tree to gui qt //////
				for (int e = 0; e < DTrFields.size(); ++e) {
						model->setHorizontalHeaderItem(e,new QStandardItem(DTrFields.at(e)));
				}
	
	
				newnames->clear();
        newnames->addItem(tr("Radice"),0);
        for (int i = 0; i < ReadModel->rowCount(); ++i) {
            QString spacer ="";
            QSqlRecord r = ReadModel->record(i);
            int LLevel =  r.value("level").toInt();
            QString cpaL = r.value("cpa").toString();
                          for (int re = 0; re < LLevel; ++re) {
                              spacer.append(".");
                          }
								if (LLevel == 3) {
									
								} else {
									cpaL ="Cat.";
								}
						newnames->addItem(cpaL+")"+spacer+"/"+r.value("name").toString(),r.value("id").toInt());
        }
	
	
	
	
	
	
	   
			 if (ReadModel->rowCount() > 0) {
        for (int i = 0; i < ReadModel->rowCount(); ++i) {
              QSqlRecord recordio = ReadModel->record(i);
              if (recordio.value("level").toInt() == 1) {
                 model->invisibleRootItem()->appendRow(Compose(i));
              }
            
        }
       }
			 
			  connect(pushButton, SIGNAL(clicked() ), this , SLOT(NewCat() )); 
			  treeView->setModel(model);
				treeView->expandAll();
				for (int e = 0; e < DisplayFields.size(); ++e) {
				treeView->resizeColumnToContents(e);  
				}
				//////////treeView->hideColumn(DisplayFields.size() - 1); 
				treeView->setEditTriggers(QAbstractItemView::NoEditTriggers);
				treeView->setSortingEnabled(false);
				treeView->setSelectionBehavior(QAbstractItemView::SelectRows);
				treeView->setSelectionMode(QAbstractItemView::NoSelection);
				treeView->setAlternatingRowColors(true);
				connect(treeView, SIGNAL(activated(QModelIndex)), this, SLOT(ActiveTre(QModelIndex)));
				connect(treeView, SIGNAL(clicked(QModelIndex) ), this , SLOT(ActiveTre(QModelIndex) ));
				
				connect(treeprint, SIGNAL(clicked() ), this , SLOT(PrintCat() ));  
        connect(bexport, SIGNAL(clicked() ), this , SLOT(Exporter() ));  
		
	
}


void GRegion::ActiveTre( QModelIndex index )
{
    if (!index.isValid()) {
    return;
    }
    int rowsres = index.model()->data(index,Qt::UserRole).toInt();
    LastIdEdit = rowsres;
    EnableEdit(rowsres);
}

void GRegion::EnableEdit( const int id )
{
     
            QSqlRecord r = ReadModel->record(id);
            
            int disponifigli = r.value("childs").toInt();
            int level = r.value("level").toInt();
            int upper = r.value("upper").toInt();
    
                ///////////////qDebug() << "beccato  " << id; /////////////////lineEdit_2->setText("");
                lineEdit_6->setText(r.value("name").toString());
	              lineEdit_3->setText(r.value("cpa").toString());
	              lineEdit_4->setText(r.value("msm").toString());
                lineEdit_8->setText(r.value("import_id").toString());
								label_2->setText(tr("Nome: /%1").arg(id));
                QAction *showFAKT = new QAction(tr("Salva"),this);
                showFAKT->setData(id);   /* int id faktura to show */
                showFAKT->setIcon(QIcon(QString::fromUtf8(":/save/img/save/filesaveas.png")));
                connect(showFAKT, SIGNAL(triggered()),this,SLOT(SaveIDs()));
                toolButton->setDefaultAction(showFAKT);
                QAction *showFAKTa = new QAction(tr("Elimina"),this);
                showFAKTa->setIcon(QIcon(QString::fromUtf8(":/default/img/default/delete.png")));
                showFAKTa->setData(id);   /* int id faktura to show */
                connect(showFAKTa, SIGNAL(triggered()),this,SLOT(RemoveIDs()));
                toolButton_2->setDefaultAction(showFAKTa);
                toolButton->setEnabled(true);
                QAction *showFAKTb = new QAction(tr("Sposta su"),this);
                showFAKTb->setIcon(QIcon(QString::fromUtf8(":/default/img/default/File_up.png")));
                showFAKTb->setData(id);   /* int id faktura to show */
                connect(showFAKTb, SIGNAL(triggered()),this,SLOT(MoveIDs()));
                move_up->setDefaultAction(showFAKTb);
                
                if (upper == 1) {
                move_up->setEnabled(true);
                } else {
                move_up->setEnabled(false);  
                }
    
                if (disponifigli == 0) {
                toolButton_2->setEnabled(true); 
                } else {
                toolButton_2->setEnabled(false);  
                }
            
     
}



QList<QStandardItem *> GRegion::Compose( int rowposition )
{
    QSqlRecord r = ReadModel->record(rowposition);
    int level;
    int childs;
    
    QFont bold_base_font = qApp->font();
    bold_base_font.setBold ( true );
    
    QString RowPositionString,DBid;
    RowPositionString.setNum(rowposition);
    QList<QStandardItem *> diritto;
    for (int x = 0; x < DisplayFields.size(); ++x) {
                    level = r.value("level").toInt();
                    childs = r.value("childs").toInt();
                    DBid = r.value("id").toString();
                    const QString Fname = DisplayFields.at(x).toLower();
			              ////////////qDebug() << " Fname " << Fname;
                    QStandardItem *item = new QStandardItem(r.value(Fname).toString());
                    item->setFlags ( Qt::ItemIsEnabled );
			              item->setData(rowposition,Qt::UserRole);
			              item->setToolTip ("["+Fname+"] lev."+r.value("level").toString());
                    if (x == 0) {
                        if (level == 3 ) {
                        item->setIcon ( QIcon(QString::fromUtf8(":/img/cassa_movimento.png")) );  
                        } else {
                        
                        item->setIcon ( QIcon(QString::fromUtf8(":/img/info.png")) );
                        }
                        
                        
                    }
                    if (x == 2 && level != 3) {
                        item->setData(bold_base_font,Qt::FontRole);
                    }
                    diritto.append(item);
    }
    
    if (!OnBox(rowposition)) {
       RowUnique.insert(rowposition,level); 
    }
    
    if (childs > 0 ) {
        for (int i = 0; i < childs; ++i) {
        const int jumpto = i + 1 + rowposition;
          if (!OnBox(jumpto)) {  
              diritto.first()->appendRow(Compose(jumpto));
          }
        }
    }
return diritto;
}







bool GRegion::OnBox( int rowposition )
{
   bool having = false;
   QMapIterator <int,int> i(RowUnique);
     while (i.hasNext()) {
           i.next();
           if ( rowposition == i.key()) {
            having = true;   
           }
    }
return having;
}


QSqlRecord GRegion::getNode( int nodeid )
{

    QString idstr,sql;
            idstr.setNum(nodeid);
    QString table(TABELLA_PAESI);
		if (nodeid > 0) {
                  sql = "SELECT "
						"n.*, "
						"round((n.rgt - n.lft-1)/2,0) AS childs "
					    " FROM "
						" "+table+" AS n "
                        " WHERE " 
                        " n.id = "+idstr+" ";
            
           /////////////// qDebug() << " sql  " << sql;
			if (query.exec(sql)) {
            return Fill_Record( query );
			} else {
            return QSqlRecord();
            }
            
      }
      return QSqlRecord();
}


void GRegion::NewCat()
{
    QString idstr,sql,name,newnummerconta,nexter;
    QString table(TABELLA_PAESI); 
    int ultimoNumeroIndice;    
    name = G_Quote(lineEdit_2->text());
    if (name.size() < 3) {
    return;
    }
    
    QDateTime now = QDateTime::currentDateTime();
    const uint anumms = now.toTime_t();
    
    if (query.exec(QString("select MAX(cpa) + 1 AS tot from %1 ").arg(table))) {
        QSqlRecord rei = Fill_Record(query);
        ultimoNumeroIndice = rei.value("tot").toInt();
        if (ultimoNumeroIndice < 1) {
           newnummerconta.setNum(1);   /* tabella vuota */
        } else {
           newnummerconta.setNum(ultimoNumeroIndice);
        }
				newnummerconta.setNum(0); 
        
        /////////QMessageBox::warning(0, tr("SQL Error"),tr("Il prossimo numero sara: %1").arg(newnummerconta));
        
        
    } else {
      QMessageBox::warning(0, tr("SQL Error"),tr("Error message: %1 \n%2").arg(query.lastError().text()).arg(query.lastQuery ()));
      return;
    }
    
    int DBid = newnames->itemData(newnames->currentIndex()).toInt();
     if (DBid > 0) {
         
         //////////qDebug() << " parente  " << DBid;
         /////////////qDebug() << " nuovo sub  " << newnummerconta;
         
         
         QSqlRecord r = getNode(DBid);
         if (r.count() < 1) {
         return;
         }
         idstr.setNum(DBid);
         nexter.setNum(r.value("rgt").toInt() + 1);
         
         ///////////qDebug() << " child to  " << r.value("root_id").toString();
         //////////////qDebug() << " child to  " << r.count();
         
                // update existing nodes
				sql = QString("UPDATE "+table+" SET lft = lft + 2 "
						      " WHERE 	root_id="+r.value("root_id").toString()+" AND "
								" lft>"+r.value("rgt").toString()+" "
                                " AND rgt>="+r.value("rgt").toString()+" ");
                if (!query.exec(sql)) {
                    QMessageBox::warning(0, tr("SQL Error"),tr("Error message: %1 \n%2").arg(query.lastError().text()).arg(query.lastQuery ()));
                    return;
                }
                sql = QString("UPDATE "+table+" SET rgt=rgt+2 WHERE "
							  " root_id="+r.value("root_id").toString()+" AND "
                              " rgt>="+r.value("rgt").toString()+" ");
                if (!query.exec(sql)) {
                    QMessageBox::warning(0, tr("SQL Error"),tr("Error message: %1 \n%2").arg(query.lastError().text()).arg(query.lastQuery ()));
                    return;
                }
                // insert new node
                sql = QString("INSERT INTO "+table+" (id,root_id,name,lft,rgt,cpa)  "
						" VALUES  (NULL,"+r.value("root_id").toString()+",'"+name+"',"+r.value("rgt").toString()+","+nexter+","+newnummerconta+") ");
                if (!query.exec(sql)) {
                    QMessageBox::warning(0, tr("SQL Error"),tr("Error message: %1 \n%2").arg(query.lastError().text()).arg(query.lastQuery ()));
                    return;
                } else {
                    lineEdit_2->setText("");
                    init();
                }
         
         
         
         
     } else {
         ////////////////qDebug() << " direct to root .... ";
         sql = "INSERT INTO "+table+" (root_id,name,lft,rgt,cpa) VALUES (0,'"+name+"',1,2,0)";
         if (query.exec(sql)) {
             
             sql = "SELECT 	id "
					"FROM 	"+table+" "
                    " WHERE root_id=0";
             if (query.exec(sql)) {
                 QSqlRecord r = Fill_Record(query);
                 ////////qDebug() << " new one  " << r.value("id").toString();
                    sql = "UPDATE	"+table+" "
					       " SET root_id="+r.value("id").toString()+" "
					         " WHERE id="+r.value("id").toString()+" ";
                           if (query.exec(sql)) {
                               lineEdit_2->setText("");
                               init();
                           } else  {
                               QMessageBox::warning(0, tr("SQL Error"),tr("Error message: %1 \n%2").arg(query.lastError().text()).arg(query.lastQuery ()));
                           }
             } else {
                 QMessageBox::warning(0, tr("SQL Error"),tr("Error message: %1 \n%2").arg(query.lastError().text()).arg(query.lastQuery ()));
             }
             
         } else {
             QMessageBox::warning(0, tr("SQL Error"),tr("Error message: %1 \n%2").arg(query.lastError().text()).arg(query.lastQuery ()));
         }
     }
}



QSqlRecord GRegion::Fill_Record( QSqlQuery q ) 
{
                 QSqlRecord r = q.record();
                  while (q.next()) { 
                    for(int i=0;i<r.count();i++){
                        ///////////////qDebug() << "fill " << i << "  ->" << q.value(i).toString();
                        r.setValue(r.fieldName(i),q.value(i));
                    }
                  }
                  return r;
}



void GRegion::RemoveIDs()
{
    QAction *textAction = qobject_cast<QAction *>(sender());
    const int id = textAction->data().toInt();
    QSqlRecord r = ReadModel->record(id);
    int disponifigli = r.value("childs").toInt();
    if (disponifigli !=0) {
    QMessageBox::warning(0, tr("SQL Error"),tr("Please remove childs on %1!").arg(id));
    return;
    }
    /////////////////qDebug() << "remove  " << id;
    QString msgDB =tr("You are sure to remove %1?").arg(r.value("name").toString());
    int removeyes = QMessageBox::question(0, tr("Please confirm"),msgDB,
                                                            tr("&Yes"), tr("&No"),
                                                             QString(),8888,9999);
    if (removeyes !=0) {
    return;
    }
    
    QString a1 = QString("UPDATE %1 SET lft=lft-2 WHERE	lft >%3 AND root_id =%2").arg(TABELLA_PAESI).arg(r.value("root_id").toInt()).arg(r.value("lft").toInt());
    QString a2 = QString("UPDATE %1 SET rgt=rgt-2 WHERE	rgt >%3 AND root_id =%2").arg(TABELLA_PAESI).arg(r.value("root_id").toInt()).arg(r.value("rgt").toInt());
    QString a3 = QString("DELETE FROM %1 WHERE id=%2 LIMIT 1").arg(TABELLA_PAESI).arg(r.value("id").toInt());
    
    if (query.exec(a1) && query.exec(a2) && query.exec(a3)) {
        init();
    } else {
        QMessageBox::warning(0, tr("SQL Error"),tr("Unable to remove id %1!").arg(r.value("id").toInt()));
    }
}


void GRegion::MoveIDs()
{
    QAction *textAction = qobject_cast<QAction *>(sender());
    const int id = textAction->data().toInt();
    /////qDebug() << "move   " << id;
    QSqlRecord r = ReadModel->record(id);
    int iddb = r.value("id").toInt();
    QString idstr,sql,name,subid,root_id,sdec,sinc;
            idstr.setNum(iddb);
    QString table(TABELLA_PAESI);
    root_id = r.value("root_id").toString();
    //////qDebug() << "move start  " << r.value("name").toString() << "  ->" << iddb;
    sql = QString("SELECT n1.root_id,n1.name n1name, n1.lft n1lft, n1.rgt n1rgt,n2.name n2name, n2.lft n2lft, n2.rgt n2rgt ");
    sql.append(QString("FROM %1 AS n1 LEFT OUTER JOIN %1 AS n2 ON (n1.lft = (n2.rgt+1) AND n1.rgt > n2.rgt AND n1.root_id = n2.root_id) WHERE n1.id=%2 LIMIT 1").arg(table).arg(iddb));
    /////////////qDebug() << "sql  " << sql;
    
           if (query.exec(sql)) {
               
               QSqlRecord  r2 = Fill_Record( query );
               if (r2.value("n2name").toString().size() > 0 && 
                   r2.value("n1name").toString().size() > 0 &&
                   r2.value("n2lft").toInt() > 0 &&
                   r2.value("n1lft").toInt() > 0) {
                       
								int desc = r2.value("n1lft").toInt() - r2.value("n2lft").toInt();
		            int inc = r2.value("n1rgt").toInt() -  r2.value("n2rgt").toInt();
                       
                    QString sqlup = QString("UPDATE %1 ").arg(table);
                    QString xcalu = QString("SET lft=lft + IF(lft<%1,%2,-%3),rgt=rgt + IF(rgt<%1,%2,-%3) ").arg(r2.value("n1lft").toInt()).arg(inc).arg(desc);
                    sqlup.append(xcalu);
                    sqlup.append(QString("WHERE	root_id= %1 AND lft>=%2 ").arg(r2.value("root_id").toInt()).arg(r2.value("n2lft").toInt()));
                    sqlup.append(QString("AND rgt<=%1  ").arg(r2.value("n1rgt").toInt()));
                       if (query.exec(sqlup)) {
                         init(); 
                        return;
                       } else {
                           QMessageBox::warning(0, tr("SQL Error"),tr("Error message: %1 \n%2").arg(query.lastError().text()).arg(query.lastQuery ()));
                           
                       }
                  QMessageBox::warning(0, tr("SQL Error"),tr("0 Swap %1 and %2 ....").arg(r2.value("n1name").toString()).arg(r2.value("n2name").toString()));
                  return;
               } else {
                   QMessageBox::warning(0, tr("SQL Error"),tr("Swap %1 and %2 error").arg(r2.value("n1name").toString()).arg(r2.value("n2name").toString()));
               }
               
               return;
           }  else {
               QMessageBox::warning(0, tr("SQL Error"),tr("Name %1 not have parent!").arg(r.value("name").toString()));
               
           }
    
}

int  GRegion::Translate_Id_Pos( const int dbid ) 
{

         for (int i = 0; i < ReadModel->rowCount(); ++i) {
              QSqlRecord recordio = ReadModel->record(i);
              if (recordio.value("id").toInt() == dbid) {
                 return i;
              }
            
        }
				return 0;
}


void GRegion::SaveIDs()
{
    QAction *textAction = qobject_cast<QAction *>(sender());
    const int id = textAction->data().toInt();
    /////////qDebug() << "salvo  " << id;
	  ///////int onrow = Translate_Id_Pos(id);
    QSqlRecord r = ReadModel->record(id);
	  const int levi = r.value("level").toInt();
	  ////////////qDebug() << "level  " << levi;
	  ////////qDebug() << "onrow  " << onrow;
    int iddb = r.value("id").toInt();
    QString idstr,sql,name,subid,metri,importid;
            idstr.setNum(iddb);
    QString table(TABELLA_PAESI);
	  subid = "0";
    importid = "0";
	  metri = "-";
	  if ( levi > 2) {
		subid = QString(lineEdit_3->text());
		metri = G_Quote(lineEdit_4->text());
    if (lineEdit_8->text().trimmed().toInt() > 0) {
    importid = QString(lineEdit_8->text());
    }
        
		}
	
    name = G_Quote(lineEdit_6->text());
    sql = QString("UPDATE  "+table+" "
							"SET name ='"+name+"',cpa='"+subid+"',msm='"+metri+"',import_id='"+importid+"' "
							"WHERE id="+idstr+" limit 1");
		
		///////////qDebug() << "sql  " << sql;
		
    if (query.exec(sql)) {
        init();
    } else {
        QMessageBox::warning(0, tr("SQL Error"),tr("Error message: %1 \n%2").arg(query.lastError().text()).arg(query.lastQuery ()));
    }
}




void GRegion::PrintCat()
{
	  ModelConverter mk;
									 mk.set(ReadModel);
    QTextDocument *doctree = mk.TabletoDom();
    TextPrinter *textprinter_ = new TextPrinter(this);
    textprinter_->setHeaderSize(12);
    textprinter_->setHeaderText(tr("Stampato il %1").arg(QDateTime::currentDateTime().toString()));
    textprinter_->preview(doctree, tr("Anteprima di stampa"));  
}

void GRegion::Exporter()
{
    ModelConverter mk;
									 mk.set(ReadModel);
    QTextDocument *doctree = mk.TabletoDom();
    
         DataExportDialog *xexport =  new DataExportDialog(this,ReadModel,true);
         xexport->SetTable(TABELLA_PAESI);
         xexport->SetDoc(doctree);
         int cango = xexport->exec();
         if (cango == 1) {
             xexport->doExport();
         }
    
}



GRegion::~GRegion()
{

}








